# -*- coding:utf-8 -*-


class FormatUtil:
    def __init__(self):
        self.common_fields = self.get_common_field()

    def get_common_field(self):
        return ['productid', 't', 'ip', 'imei', 'model', 'imsi', 'uid', 'uuid', 'rom', 'ver', 'ch', 'cc', 'prov',
                'isp', 'net', 'mac', 'sn', 'aid', 'rid', 'amap', 'puid', 'utdid', ]

    def get_clean_line(self, logcat_line_str):
        return logcat_line_str[logcat_line_str.find("logAsyncInteral:") + len("logAsyncInteral:"):]

    def get_clean_fields(self, logcat_line_str, need_comm=False):
        """:return fields dict with/without common fields"""
        line_clean = self.get_clean_line(logcat_line_str)
        fields_line = line_clean.split("`")
        fields_dict = {}
        for field in fields_line:
            temp_key_value_list = field.split("=")
            if temp_key_value_list[0] < 1:
                continue
            if len(temp_key_value_list) > 1:
                if len(temp_key_value_list[1]):
                    fields_dict[temp_key_value_list[0]] = temp_key_value_list[1]
            # else:
            #     fields_dict[temp_key_value_list[0]] = ""
        if need_comm:
            # return self.dict_to_sorted_str(fields_dict)
            return fields_dict
        else:
            fields_dict_without_comm = {}

            for key in fields_dict:
                if key not in self.common_fields:
                    fields_dict_without_comm[key] = fields_dict[key]
            return fields_dict_without_comm

    def dict_to_sorted_str(self, temp_dict):
        temp_list = []
        for key in temp_dict:
            temp_list.append(key+"="+temp_dict[key])
        return "`".join(sorted(temp_list))

    def dict_to_sorted_str_by_preinstall(self, temp_dict):
        sorted_table = ['logtype', 'module', 'page', 'action', 'ck_url', 'resType', 'position', 'app_id', 'app_name',
                        'keyword', 'pack_id', 'f', 'ex_a', 'ex_b', 'ex_c', 'ex_d', 'source', 'r_json', '']
        result_list = []
        for key in sorted_table:
            if key in temp_dict:
                result_list.append(key+"="+temp_dict[key])
                temp_dict.pop(key)
        custom_fields = []
        for key in temp_dict:
            custom_fields.append(key+"="+temp_dict[key])
        result_list += sorted(custom_fields)
        return "`".join(result_list)

    def logcat_format(self, logcat_line_str, need_comm=False):
        fields_dict = self.get_clean_fields(logcat_line_str, need_comm)
        return self.dict_to_sorted_str_by_preinstall(fields_dict)
